<template>
  <div class="setting-page">
    <div class="setting-content">
      <p class="title">录制参数设置</p>
      <div class="form-block">
        <el-form @submit.native.prevent label-position="left" label-width="200px">
          <el-row align="top" :gutter="10">
            <el-col :span="24">
              <el-form-item label="输出路径:">
                <el-input v-model="paramsForm.outputpath" disabled placeholder="请输入路径" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="mcap包生成周期:">
                <el-input v-model.number="paramsForm.maxduration" placeholder="默认30s"
                  oninput="value=value.replace(/[^0-9]/g,'')" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="录制速腾激光雷达:" class="recordpcap">
                <el-switch style="--el-switch-on-color: #6180f4; " v-model="paramsForm.recordpcap"
                  :disabled="isStart" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="录制音视频信号:" class="recordpcap">
                <el-switch style="--el-switch-on-color: #6180f4; " v-model="paramsForm.recordvideo"
                  :disabled="isStart" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="loading_color">
              <el-form-item label="录制真值pcap:" class="recordpcap">
                <el-switch style="--el-switch-on-color: #6180f4; " :disabled="isStart" :loading="cptLoading"
                  v-model="paramsForm.record_notzj_cpt" @change="(val) => canfdZZChange(val)" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="loading_color">
              <el-form-item label="canfd信号(60S/包):" class="recordpcap">
                <el-switch style="--el-switch-on-color: #6180f4; " :disabled="isStart" :loading="canfd800Loading"
                  v-model="paramsForm.record_notzj_canfd_800" @change="(val) => canfd800Change(val)" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="loading_color">
              <el-form-item label="canfd信号(不分包):" class="recordpcap">
                <el-switch style="--el-switch-on-color: #6180f4; " :disabled="isStart"
                  :loading="canfd800NotSplitLoading" v-model="paramsForm.recordCanfdNotSplit"
                  @change="(val) => canfd800NotSplitChange(val)" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <p class="title">录制事件设置(总数/
        <span class="redText">异常数</span>
      )</p>

      <div class="event-main">
        <el-button type="primary" color="#6180f4" class="refresh-eventlist-btn" @click="resetEvent()">
          同步事件列表
          <el-icon class="el-icon--right">
            <Refresh />
          </el-icon>
        </el-button>
        <div class="main">
          <div v-if="eventLoading" v-loading="eventLoading" class="eventLoading"></div>
          <div class="event-group" v-else :class="'event-group-' + index"
            v-for="(item1, index) in recordEventOriginData">
            <!-- <p class="event-group-title"> {{ item1.recordTypeTitle }}</p> -->
            <div class="tree">
              <el-tree :ref="(el) => setTreeRefs(el, index)" :data="item1.recordEventList" node-key="treeId" show-checkbox
                @check-change="handleCheckChange(index, item1.recordType)"
                :props="{ children: 'children', label: 'label', disabled: function (data, node) { return isStart } }">
                <template #default="{ node, data }">
                  <span class="el-tree-node__label">
                    <span :style="{ color: data.isPenultimate ? 'red' : '' }">
                      {{ node.label }}&nbsp;&nbsp;
                      <span style="color:#333;" v-if="node.level == 1">{{ data.sum }}/<f style="color:red;">{{
            data.errorSum }}</f></span>
                    </span>
                    <el-tooltip v-if="node.level !== 1" class="box-item" effect="dark" :content="data.event"
                      placement="top-start" popper-class="home-tooltip">
                      <span class="el-icon-question"></span>
                    </el-tooltip>
                  </span>
                </template>
              </el-tree>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="setting-footer">
      <el-button color="#6180f4" plain @click="cancelSetParams()">取消</el-button>
      <el-button type="primary" color="#6180f4" style="--el-button-text-color:#fff;--el-button-hover-text-color:#fff"
        @click="confirmSetParams()">确定</el-button>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, nextTick,toRaw, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { checkZZSignal, check800Signal, getEventlistType, parameterSetting,syncRemoteDataEvent } from '@/api/settingVideo.js'
import { isNonEmptyObject } from '@/utils/util.js'

defineOptions({
  name: 'VideoParams'
})
const emit = defineEmits(['closeSettingDrawer'])
const props = defineProps({
  reviewParamsForm: {
    type: Object,
    default: {}
  },
  // reviewTreeGroupData: {
  //   type: Array,
  //   default: []
  // }
})
let paramsForm = ref({
  outputpath: '/opt/usr/Nas/',
  maxduration: 30,
  recordpcap: false,  // 录制速腾激光雷达信号
  recordvideo: false,  // 录制音视频信号
  record_notzj_cpt: false,  //录制真值pcap
  record_notzj_canfd_800: false, // canfd信号(60S/包)
  recordCanfdNotSplit: false,   // canfd信号(不分包)
})
let isStart = ref(false)
let cptLoading = ref(false)
let canfd800Loading = ref(false)
let canfd800NotSplitLoading = ref(false)
let eventLoading = ref(false)
let recordEventOriginData = ref([]) // 事件组的原数据
// let reviewTreeGroup = []  // 回显的事件组数据
let submitEventParams = reactive([])
let treeRefs = []
let setTreeRefs = (el, index) => {
  if (el) {
    treeRefs.push({
      id: index,
      el
    })
  }
}
// let reviewTreeGroup = computed(()=> {
//   return props.reviewTreeGroupData.length > 0 ? props.reviewTreeGroupData.map((item) => item.recordEventList.map(item2 => item2.treeId)).flat() : []
// })
onMounted(() => {
  // reviewParamsForm不是空，则赋值给paramsForm 回显 
  if(isNonEmptyObject(toRaw(props.reviewParamsForm))){
    paramsForm.value = props.reviewParamsForm
  }
  // reviewTreeGroup = props.reviewTreeGroupData.map((item) => item.recordEventList.map(item2 => item2.treeId)).flat()
  // console.log('reviewTreeGroup mounted' ,reviewTreeGroup)
  setTimeout(() => {
    getEventlist()
  }, 3000);
})

// 检测真值
let canfdZZChange = (val) => {
  paramsForm.value.record_notzj_cpt = false
  cptLoading.value = true
  if (val) {
    checkZZSignal()
      .then((response) => {
        if (response && response.status == 200) {
          let data = response.data.data
          if (data) {
            paramsForm.value.record_notzj_cpt = true
          } else {
            ElMessage.error("当前真值pcap设备不可用")
          }
        }
      }).catch((err) => {

      }).finally(() => {
        cptLoading.value = false
      })
  }
}
// 检测800U
let canfd800Change = (val) => {
  if (val) {
    paramsForm.value.record_notzj_canfd_800 = false //防止先开启
    canfd800Loading.value = true
    check800Signal()
      .then((response) => {
        if (response && response.status == 200) {
          let data = response.data.data
          if (data) {
            paramsForm.value.record_notzj_canfd_800 = true
          } else {
            ElMessage.error("当前canfd信号(60S/包)设备不可用")
          }
        }
      }).catch((err) => {

      }).finally(() => {
        canfd800Loading.value = false
      })
  }
}
// canfd 不分包信号
let canfd800NotSplitChange = (val) => {
  if (val) {
    paramsForm.value.recordCanfdNotSplit = false //防止先开启
    canfd800NotSplitLoading.value = true
    check800Signal()
      .then((response) => {
        if (response && response.status == 200) {
          let data = response.data.data
          if (data) {
            paramsForm.value.recordCanfdNotSplit = true
          } else {
            ElMessage.error("当前canfd信号(不分包)设备不可用")
          }
        }
      }).catch((err) => {

      }).finally(() => {
        canfd800NotSplitLoading.value = false
      })
  }
}
// 事件分类列表
let getEventlist = () => {
  eventLoading.value = true
  getEventlistType()
    .then((response) => {
      if (response && response.status == 200) {
        let originData = response.data.data || []
        originData.forEach((item1) => {
          if (Array.isArray(item1.recordEventList)) {
            item1.recordEventList.forEach((item2) => {
              item2.label = item2.groupname
              item2.children = []
              if (Array.isArray(item2.eventList)) {
                item2.eventList.forEach((item3) => {
                  item2.children.push(
                    {
                      label: ((item3.sensorname || '无')),
                      id: item3.id,
                      groupEventRelDomainId: item3.groupEventRelDomainId,
                      event: item3.event,
                      isPenultimate: item3.exsit.indexOf('不存在') != -1 ? true : false,
                      sum: item3.sum,
                      errorSum: item3.errorSum,
                      treeId: item3.treeId
                    }
                  )
                })
              }
            });
          }
        });
        recordEventOriginData.value = originData
        // 树的回显功能未联调成功
      }
    })
    .catch((err) => {
      // ElMessage.error("接口请求失败，请检查网络")
    }).finally(() => {
      eventLoading.value = false
    });
}
//选择分类事件
let handleCheckChange = (treeIndex, recordType) => {
  let obj = {
    recordType: recordType,
    recordEventList: [],
  }

  let selectList = treeRefs[treeIndex].el.getCheckedNodes()
  let recordEventList = []
  selectList.map((item) => {
    if (item && item.id) {
      recordEventList.push({
        eventName: item.event,
        eventId: item.id,
        treeId: item.treeId,
        eventGroupRelDomainId: item.groupEventRelDomainId,
      })
    }
  })
  obj.recordEventList = recordEventList
  let recordTypeIndex = submitEventParams.findIndex(it => it.recordType === recordType)
  if (recordTypeIndex === -1) {
    if (selectList && selectList.length > 0) {
      submitEventParams.push(obj)
    }
  } else {
    if (selectList && selectList.length > 0) {
      submitEventParams.splice(recordTypeIndex, 1, obj)
    } else {
      submitEventParams.splice(recordTypeIndex, 1)
    }

  }
}
let cancelSetParams = () => {
  emit('closeSettingDrawer')
}
let confirmSetParams = () => {
  submitSettingData()
}
let submitSettingData = () => {
  if (submitEventParams.length <= 0) {
    // if(this.hasSettingData){
    //     ElMessage.error('未设置任何录制项目，沿用上一次设置')
    //     return
    // }
    ElMessage.error('请先设置录制事件')
    return
  }
  let path = paramsForm.value.outputpath || ''
  let params = {
    outputpath: path ? (path.charAt(path.length - 1) != '/' ? path + '/' : path) : '',
    maxduration: parseInt(paramsForm.value.maxduration || 30),
    recordpcap: paramsForm.value.recordpcap,
    record_notzj_cpt: paramsForm.value.record_notzj_cpt,
    record_notzj_canfd_800: paramsForm.value.record_notzj_canfd_800,
    recordCanfdNotSplit: paramsForm.value.recordCanfdNotSplit,
    recordvideo: paramsForm.value.recordvideo,
    // 新增1个 事件组的字段 发送给后端
    recordParams: submitEventParams,
  }
  // 设置录制参数
  parameterSetting(params)
    .then((response) => {
      if (response && response.status == 200) {
        let data = response.data.data
        if (data == '成功') {
          ElMessage.success('录制参数保存成功')
        }
      }
    })
    .catch((err) => {
      ElMessage.error('录制参数保存失败')
    }).finally(() => {
      emit('closeSettingDrawer', true)
    });
}

// 同步云事件
const resetEvent = () => {
  eventLoading.value = true
  syncRemoteDataEvent()
    .then((response) => {
      if (response && response.status == 200) {
        if (response.data.data) {
          // 获取分类事件
          getEventlist()
        }
      } else {
      }
    })
    .catch((err) => {
      console.log('同步云事件失败');
    }).finally(() => {
      eventLoading.value = false
    });
}
</script>

<style scoped>
.purple-text {
  color: #6180f4;
}

.purple-bg {
  background: #6180f4;
}

.setting-page {
  position: relative;
  height: 100%;
}

.setting-content {
  padding: 20px;
  height: calc(100% - 80px);
  overflow: auto;
}

.setting-footer {
  margin-top: 16px;
  border-top: 1px solid #ddd;
  padding: 20px;
  text-align: right;
  position: absolute;
  bottom: 0;
  right: 0;
  width: 100%;
}

.title {
  text-align: left;
  font-weight: bold;
  padding-left: 10px;
  border-left: 5px solid #6180f4;
  margin-bottom: 30px;
  background: #eef2ff;
  padding: 10px;
}

.form-block {
  margin-bottom: 40px;
  padding-bottom: 16px;
}

/* 事件树的样式 */
.event-main {
  margin-top: 2%;
  text-align: left;

  .refresh-eventlist-btn {
    color: #fff;
  }

  .title {
    position: relative;
    background: rgb(217, 222, 227);

    span {
      font-size: 14px;
      margin-left: 8px;

      t {
        color: red;
      }
    }
  }

  .tree {
    height: calc(100% - 60px);
    overflow-y: auto;
  }

  .main {
    margin-top: 10px;
    max-height: calc(100% - 300px);
    overflow-y: auto;
  }

  .eventLoading {
    margin-top: 20px;
    width: 60px;
    height: 60px;
    margin: 0 auto;
  }

  .event-group {
    text-align: left;
  }

  .event-group-title {
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 5px;
  }

}
</style>
<style>
.el-form-item {
  margin-bottom: 8px;
}

.el-tree-node__content {
  margin-bottom: 7px;
}

.el-form-item__label {
  font-size: 16px;
}

.el-tree-node__label {
  font-size: 1rem;
  white-space: normal;
  flex-wrap: wrap;
  width: 100%;
  display: block;
  word-break: break-all;
}

.el-checkbox__inner {
  width: 18px !important;
  height: 18px !important;
}

.el-checkbox__input.is-checked .el-checkbox__inner,
.el-checkbox__input.is-indeterminate .el-checkbox__inner {

  background-color: #6180f4 !important;
  border-color: #6180f4 !important;
}

.el-checkbox__input.is-indeterminate .el-checkbox__inner::before {
  background-color: #eaeaec !important;
  width: 12px;
  left: 1px;
  height: 5px;
  top: 5px;
}

.el-checkbox__input.is-checked .el-checkbox__inner::after {
  border-color: #eaeaec !important;
  left: 6px;
  top: 3px;
  width: 4px;
  height: 8px;
}

.el-checkbox__input.is-indeterminate .el-checkbox__inner::before {
  background-color: #eaeaec !important;
}
</style>